using System;
using HCore.Unity.Core;
using HCore.Unity.Shader;
using UnityEngine;
using UnityEngine.UI;

namespace HCore.Tests.Runtime.BlurEffect.Scripts
{
    public class BaseView : MonoBehaviour
    {
        protected BlurType BlurType = BlurType.ScreenShot;
        private GameObject mBgObj;
        private RawImage mBgRaw;
        private RenderTexture mBlurBgRT;
        protected bool NeedBlurBg = false;
        protected bool UseUIBlur = true;

        protected void Awake()
        {
            if (NeedBlurBg)
                switch (BlurType)
                {
                    // 截屏式的模糊
                    case BlurType.ScreenShot:
                    {
                        // 隐藏界面本身，因为界面本身不需要被拍入画面
                        gameObject.SetActive(false);
                        // 创建挂载模糊图片的节点，使用的是RawImage
                        mBgObj = new GameObject("blur_bg");
                        mBgObj.transform.SetParent(transform);
                        mBgObj.transform.localScale = Vector3.one;
                        mBgObj.transform.SetAsFirstSibling();
                        mBgObj.AddComponent<RectTransform>().sizeDelta = new Vector2(Screen.width, Screen.height);
                        var localPos = mBgObj.GetComponent<RectTransform>().localPosition;
                        mBgObj.GetComponent<RectTransform>().localPosition = new Vector3(localPos.x, localPos.y, 0);
                        mBgRaw = mBgObj.AddComponent<RawImage>();
                        GaussianBlurManager.Instance.GetBlurScreenshot(GetBlurCamera(), SetBlurImage);
                        break;
                    }
                    // 实时模糊效果
                    case BlurType.RealTime:
                        GaussianBlurManager.Instance.EnableBlurRender(GetBlurCamera());
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
        }

        private void OnDestroy()
        {
            GaussianBlurManager.Instance.DisabledBlurRender(GetBlurCamera());
            if (mBlurBgRT != null) RenderTexture.ReleaseTemporary(mBlurBgRT);
        }


        private Camera GetBlurCamera()
        {
            return GameUtils.UIGameCamera;
            // return GameUtils.MainCamera;
            // return UseUIBlur ? GameUtils.UICamera : GameUtils.MainCamera;
        }

        private void SetBlurImage(RenderTexture rt)
        {
            mBlurBgRT = rt;
            mBgRaw.texture = mBlurBgRT;
            gameObject.SetActive(true);
        }
    }
}